using Sheep_Breeding.Domain.production_a;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Infeartructure;
using Sheep_Breeding.Write.Api.OperationServices.IServices;
using Sheep_Breeding.Write.Api.production_a_DTO;
using Yitter.IdGenerator;

namespace Sheep_Breeding.Write.Api.OperationServices.Services
{
    /// <summary>
    /// 母羊配种服务实现类
    /// </summary>
    public class EweMatingServices : IEweMatingServices
    {
        private readonly ILogger<EweMatingServices> _logger;
        private readonly IBaseRepository<Ewe_mating> _eweMatingRepository;
        private readonly EFDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">日志记录器</param>
        /// <param name="eweMatingRepository">母羊配种仓储</param>
        /// <param name="dbContext">数据库上下文</param>
        public EweMatingServices(
            ILogger<EweMatingServices> logger,
            IBaseRepository<Ewe_mating> eweMatingRepository,
            EFDbContext dbContext)
        {
            _logger = logger;
            _eweMatingRepository = eweMatingRepository;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 新增母羊配种记录
        /// </summary>
        /// <param name="dto">母羊配种新增DTO</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> AddEweMating(AddEweMatingDto dto)
        {
            var result = new ApiResult();

            try
            {
                // 验证耳号是否已存在
                var existingEwe = _eweMatingRepository.Getlist()
                    .FirstOrDefault(x => x.EarNumber == dto.EarNumber);

                if (existingEwe != null)
                {
                    result.msg = $"耳号为 {dto.EarNumber} 的母羊已存在配种记录";
                    return result;
                }

                // 生成配种编号（使用雪花算法生成唯一ID）
                string breedingId;
                try
                {
                    breedingId = YitIdHelper.NextId().ToString();
                }
                catch (Exception ex)
                {
                    _logger.LogWarning($"雪花算法生成ID失败，使用备用方案：{ex.Message}");
                    // 备用方案：使用时间戳+随机数
                    breedingId = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999).ToString();
                }

                // 创建母羊配种实体
                var eweMating = new Ewe_mating
                {
                    BreedingId = breedingId,
                    BreedingDate = dto.BreedingDate,
                    LastBreedingDate = dto.LastBreedingDate,
                    EarNumber = dto.EarNumber,
                    FemaleBreed = dto.FemaleBreed,
                    FemaleType = dto.FemaleType,
                    FirstMaleSheep = dto.FirstMaleSheep,
                    ExtraMaleSheep = dto.ExtraMaleSheep,
                    BreedingMethod = dto.BreedingMethod,
                    FemaleEstrusType = dto.FemaleEstrusType,
                    BreedingStage = dto.BreedingStage,
                    BreedingHouse = dto.BreedingHouse,
                    BreedingPen = dto.BreedingPen,
                    Weight = dto.Weight,
                    Remark = dto.Remark,
                    Creator = dto.Creator,
                    CreateTime = DateTime.Now,
                    Modifier = dto.Creator,
                    ModifyTime = DateTime.Now
                };

                // 保存到数据库
                var addResult = await _eweMatingRepository.AddAsyn(eweMating);

                if (addResult > 0)
                {
                    result.success($"母羊配种记录添加成功，配种编号：{breedingId}");
                    _logger.LogInformation($"新增母羊配种记录成功，配种编号：{breedingId}，耳号：{dto.EarNumber}");
                }
                else
                {
                    result.msg = "母羊配种记录添加失败";
                    _logger.LogError($"新增母羊配种记录失败，耳号：{dto.EarNumber}");
                }
            }
            catch (Exception ex)
            {
                result.msg = "新增母羊配种记录时发生异常";
                _logger.LogError($"新增母羊配种记录异常：{ex.Message}，耳号：{dto.EarNumber}");
            }

            return result;
        }

        /// <summary>
        /// 批量新增母羊配种
        /// </summary>
        /// <param name="batchDto">批量新增DTO</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> AddEweMatingBatch(AddEweMatingBatchDto batchDto)
        {
            var result = new ApiResult();
            try
            {
                var list = new List<Ewe_mating>();
                foreach (var dto in batchDto.Items)
                {
                    // 生成唯一ID
                    string breedingId;
                    try
                    {
                        breedingId = Yitter.IdGenerator.YitIdHelper.NextId().ToString();
                    }
                    catch
                    {
                        breedingId = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999);
                    }

                    var entity = new Ewe_mating
                    {
                        BreedingId = breedingId,
                        BreedingDate = dto.BreedingDate,
                        LastBreedingDate = dto.LastBreedingDate,
                        EarNumber = dto.EarNumber,
                        FemaleBreed = dto.FemaleBreed,
                        FemaleType = dto.FemaleType,
                        FirstMaleSheep = dto.FirstMaleSheep,
                        ExtraMaleSheep = dto.ExtraMaleSheep,
                        BreedingMethod = dto.BreedingMethod,
                        FemaleEstrusType = dto.FemaleEstrusType,
                        BreedingStage = dto.BreedingStage,
                        BreedingHouse = dto.BreedingHouse,
                        BreedingPen = dto.BreedingPen,
                        Weight = dto.Weight,
                        Remark = dto.Remark,
                        Creator = dto.Creator,
                        CreateTime = DateTime.Now,
                        Modifier = dto.Creator,
                        ModifyTime = DateTime.Now
                    };
                    list.Add(entity);
                }

                // 批量插入
                var addResult = await _eweMatingRepository.Batchadd(list);
                if (addResult > 0)
                {
                    result.success("批量新增母羊配种成功");
                }
                else
                {
                    result.msg = "批量新增失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = "批量新增异常：" + ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 主表+明细表联合添加
        /// </summary>
        public async Task<ApiResult> AddEweMatingWithDetails(AddEweMatingWithDetailsDto dto)
        {
            var result = new ApiResult();
            try
            {
                // 生成主表ID
                string breedingId;
                try
                {
                    breedingId = YitIdHelper.NextId().ToString();
                }
                catch
                {
                    breedingId = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(1000, 9999);
                }
                // 主表实体
                var eweMating = new Ewe_mating
                {
                    BreedingId = breedingId,
                    BreedingDate = dto.BreedingDate,
                    LastBreedingDate = dto.LastBreedingDate,
                    EarNumber = dto.EarNumber,
                    FemaleBreed = dto.FemaleBreed,
                    FemaleType = dto.FemaleType,
                    FirstMaleSheep = dto.FirstMaleSheep,
                    ExtraMaleSheep = dto.ExtraMaleSheep,
                    BreedingMethod = dto.BreedingMethod,
                    FemaleEstrusType = dto.FemaleEstrusType,
                    BreedingStage = dto.BreedingStage,
                    BreedingHouse = dto.BreedingHouse,
                    BreedingPen = dto.BreedingPen,
                    Weight = dto.Weight,
                    Remark = dto.Remark,
                    Creator = dto.Creator,
                    CreateTime = DateTime.Now,
                    Modifier = dto.Creator,
                    ModifyTime = DateTime.Now
                };
                await _dbContext.Ewe_Matings.AddAsync(eweMating);
                await _dbContext.SaveChangesAsync();
                // 明细表
                var details = new List<Ewe_mating_details>();
                foreach (var d in dto.Details)
                {
                    details.Add(new Ewe_mating_details
                    {
                        BreedingId = breedingId,
                        EventId = d.EventId,
                        EventType = d.EventType,
                        EventPen = d.EventPen,
                        EventHouse = d.EventHouse,
                        TransferInPen = d.TransferInPen,
                        TransferInHouse = d.TransferInHouse,
                        PredictionStatus = d.PredictionStatus,
                        EventDate = d.EventDate,
                        EventWeight = d.EventWeight,
                        Principal = d.Principal,
                        Creator = d.Creator,
                        CreateTime = DateTime.Now,
                        DocumentNo = d.DocumentNo,
                        Auditor = "",
                        Modifier = "",
                         
                        IsDeleted = false
                    });
                }
                await _dbContext.Ewe_Matings_Details.AddRangeAsync(details);
                await _dbContext.SaveChangesAsync();
                result.success($"主表+明细表添加成功，主表ID：{breedingId}");
            }
            catch (Exception ex)
            {
                var inner = ex;
                while (inner.InnerException != null)
                    inner = inner.InnerException;
                result.msg = "主表+明细表添加异常：" + inner.Message;
            }
            return result;
        }

        /// <summary>
        /// 根据配种编号进行逻辑删除
        /// </summary>
        /// <param name="breedingId">配种编号</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> DeleteEweMating(string breedingId)
        {
            var result = new ApiResult();
            try
            {
                // 查找对应的配种记录
                var entity = _eweMatingRepository.Getlist().FirstOrDefault(x => x.BreedingId == breedingId);
                if (entity == null)
                {
                    result.msg = $"未找到配种编号为{breedingId}的记录";
                    return result;
                }
                // 逻辑删除
                entity.IsDeleted = true;
                entity.ModifyTime = DateTime.Now;
                var updateResult = await _eweMatingRepository.Update(entity);
                if (updateResult > 0)
                {
                    result.success($"配种编号为{breedingId}的记录已逻辑删除");
                }
                else
                {
                    result.msg = $"配种编号为{breedingId}的记录逻辑删除失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = $"逻辑删除时发生异常：{ex.Message}";
            }
            return result;
        }

        /// <summary>
        /// 编辑母羊配种记录
        /// </summary>
        /// <param name="dto">编辑DTO</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> UpdateEweMating(UpdateEweMatingDto dto)
        {
            var result = new ApiResult();
            try
            {
                // 查找对应的配种记录
                var entity = _eweMatingRepository.Getlist().FirstOrDefault(x => x.BreedingId == dto.BreedingId);
                if (entity == null)
                {
                    result.msg = $"未找到配种编号为{dto.BreedingId}的记录";
                    return result;
                }
                // 更新字段
                entity.BreedingDate = dto.BreedingDate;
                entity.LastBreedingDate = dto.LastBreedingDate;
                entity.EarNumber = dto.EarNumber;
                entity.FemaleBreed = dto.FemaleBreed;
                entity.FemaleType = dto.FemaleType;
                entity.FirstMaleSheep = dto.FirstMaleSheep;
                entity.ExtraMaleSheep = dto.ExtraMaleSheep;
                entity.BreedingMethod = dto.BreedingMethod;
                entity.FemaleEstrusType = dto.FemaleEstrusType;
                entity.BreedingStage = dto.BreedingStage;
                entity.BreedingHouse = dto.BreedingHouse;
                entity.BreedingPen = dto.BreedingPen;
                entity.Weight = dto.Weight;
                entity.Remark = dto.Remark;
                entity.Modifier = dto.Modifier;
                entity.ModifyTime = DateTime.Now;
                // 保存到数据库
                var updateResult = await _eweMatingRepository.Update(entity);
                if (updateResult > 0)
                {
                    result.success($"配种编号为{dto.BreedingId}的记录已成功更新");
                }
                else
                {
                    result.msg = $"配种编号为{dto.BreedingId}的记录更新失败";
                }
            }
            catch (Exception ex)
            {
                result.msg = $"编辑母羊配种记录时发生异常：{ex.Message}";
            }
            return result;
        }
    }
} 